package com.hp.bon.sgw.wh.service;

import com.hp.bon.sgw.wh.bean.BusinessRecordPort;
import com.hp.bon.sgw.wh.bean.TInterfacePassword;
import com.hp.bon.sgw.wh.bean.TmallFluxLog;
import com.hp.bon.sgw.wh.bean.TmallLog;
import com.hp.bon.sgw.wh.channel.RenewChannel;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

public class TmallLogDao {
	
	private static final Logger _log = LoggerFactory.getLogger(TmallLogDao.class);
	private static final Logger logger = LoggerFactory
			.getLogger(RenewChannel.class);
	private SessionFactory sessionFactory;
	
	@Autowired
	@Qualifier("outerSessionFactory")
	public void setSessionFactSgw(SessionFactory pSessionFact) {
		this.sessionFactory = pSessionFact;
	}

	
    @Transactional(value = "transactionManager")
	public int gettbOrderNo(String tbOrderNo){
    	 StringBuilder sb = new StringBuilder();
    	 sb.append("select count(1) from t_mall_log a where a.tbOrderNo='"+tbOrderNo+"'");
    	 Query query = sessionFactory.getCurrentSession().createSQLQuery(sb.toString());
    	 BigDecimal  a=(BigDecimal)query.list().get(0);
		 return a.intValue();
	}
    
    @Transactional(value = "transactionManager")
  	public TInterfacePassword getTInterfacePassword(){
    	logger.info("======TmallLogDao=222=====");
      	 StringBuilder sb = new StringBuilder();
      	 sb.append("From TInterfacePassword a where a.keyId = 1");
      	 Query query = sessionFactory.getCurrentSession().createQuery(sb.toString());
      	logger.info("======TmallLogDao===query====="+query.list().size());
      	 if(query.list().size()>0){
      		 return (TInterfacePassword)query.list().get(0);
      	 }
  		 return null;
  	}
    
    @Transactional(value = "transactionManager")
  	public void insertBusinessRecordPort(BusinessRecordPort bean){
    	try {
			StringBuilder sb = new StringBuilder();
			sb.append("insert into t_business_record_port (ack_validate_code,business_call_id,from_node_id,protocol_type," +//4
                    "recv_request_length,recv_request_time,recv_response_length,recv_response_time,request_host,request_ip," +//10
                    "request_time,response_host,response_time,result,result_code,result_reason,send_request_length," +//17
                    "send_request_time,send_response_length,send_response_time,service_context_id,service_result_code," +//22
                    "session_id,to_node_id,trans_direction,ack_validate_desc) values (");//26
			sb.append("0,");
			sb.append("'"+bean.getBusinessCallId()+"',");
			sb.append("0,");
			sb.append("0,");
			sb.append("0,");//5
			sb.append("'',");
			sb.append("0,");
			sb.append("'',");
			sb.append("'"+bean.getRequestHost()+"',");
			sb.append("'',");//10
			sb.append("'',");
			sb.append("'',");
			sb.append("'"+bean.getResponseTime()+"',");
			sb.append(bean.getResult()+",");
            int resultCode = bean.getResultCode() == null ? 0 : bean.getResultCode();
            sb.append(resultCode+",");//15
            String resultReason = bean.getResultReason();
            if(resultReason == null) resultReason="";
            sb.append("'"+resultReason+"',");
			sb.append("0,");
			sb.append("'',");
			sb.append("0,");
			sb.append("'',");//20
			sb.append("'"+bean.getServiceContextId()+"',");
			sb.append("0,");
			sb.append("'"+bean.getSessionId()+"',");
			sb.append("0,");
			sb.append("0,");//25
			sb.append("''");//26
			sb.append(")");

//			_log.info("sql:"+sb.toString());
//			try {
//                DatabaseMetaData metaData = sessionFactory.getCurrentSession().connection().getMetaData();
//
//                _log.info("数据库连接属性:sessionFactory1:"+metaData.getDriverName());
//                _log.info("数据库连接属性:sessionFactory2:"+metaData.getDriverVersion());
//                _log.info("数据库连接属性:sessionFactory3:"+metaData.getURL());
//                _log.info("数据库连接属性:sessionFactory4:"+metaData.getUserName());
//
//            }catch (Exception e){
//			    logger.error("",e);
//            }
			sessionFactory.getCurrentSession().createSQLQuery(sb.toString()).executeUpdate();
		} catch (Exception e) {
            _log.error("insertBusinessRecordPort error",e);

        }
  	}
    
    @Transactional(value = "w")
	public TmallLog getTmallLog(String tbOrderNo){
    	 StringBuilder sb = new StringBuilder();
    	 sb.append("From TmallLog a where a.tbOrderNo='"+tbOrderNo+"'");
    	 Query query = sessionFactory.getCurrentSession().createQuery(sb.toString());
    	 if(query.list().size()>0){
    		 return (TmallLog)query.list().get(0);
    	 }
		 return null;
	}
    
    @Transactional(value = "transactionManager")
	public TmallFluxLog getTmallFluxLog(String tbOrderNo){
    	 StringBuilder sb = new StringBuilder();
    	 sb.append("From TmallFluxLog a where a.tbOrderNo='"+tbOrderNo+"'");
    	 Query query = sessionFactory.getCurrentSession().createQuery(sb.toString());
    	 if(query.list().size()>0){
    		 return (TmallFluxLog)query.list().get(0);
    	 }
		 return null;
	}
    
	@Transactional(value = "transactionManager")
	public void insertLog(TmallLog bean){
		try {
			StringBuilder sb = new StringBuilder();
			sb.append("insert into t_mall_log (tbOrderNo,accountVal,timeStart,flag) values (");
			sb.append("'"+bean.getTbOrderNo()+"',");
			sb.append("'"+bean.getAccountVal()+"',");
			sb.append("'"+bean.getTimeStart()+"',");
			sb.append("'"+bean.getFlag()+"'");
			sb.append(")");
			_log.debug("sql:"+sb.toString());
			sessionFactory.getCurrentSession().createSQLQuery(sb.toString()).executeUpdate();
		} catch (Exception e) {
		}
	}
	
	
	@Transactional(value = "transactionManager")
	public void updateTmallLog(TmallLog tmallLog) {
		StringBuilder sb = new StringBuilder();
		sb.append("update t_mall_log set flag="+tmallLog.getFlag());
		if(tmallLog.getCoopOrderNo()!=null){
			sb.append(",coopOrderNo='"+tmallLog.getCoopOrderNo()+"'");
		}
		sb.append(" where tbOrderNo='"+tmallLog.getTbOrderNo()+"'");
		_log.debug("sql:"+sb.toString());
		sessionFactory.getCurrentSession().createSQLQuery(sb.toString()).executeUpdate();
	}
	
	
	@Transactional(value = "transactionManager")
	public void insertTmallFluxLog(TmallFluxLog bean) {
		_log.debug("insertTmallFluxLog  sql start");
		try {
			StringBuilder sb = new StringBuilder();
			sb.append("insert into t_mall_flux_log (tbOrderNo,accountVal,timeStart,SalesIndentId,CustIndentNbr,spuId,totalPrice,tbPrice,LatnId,flag) values (");
			sb.append("'"+bean.getTbOrderNo()+"'");
			sb.append(",'"+bean.getAccountVal()+"'");
			sb.append(",'"+bean.getTimeStart()+"'");
			
			if(bean.getSalesIndentId()!=null){
				sb.append(",'"+bean.getSalesIndentId()+"'");
			}else{
				sb.append(",''");
			}
			if(bean.getCustIndentNbr()!=null){
				sb.append(",'"+bean.getCustIndentNbr()+"'");
			}else{
				sb.append(",''");
			}
			sb.append(",'"+bean.getSpuId()+"'");
			sb.append(",'"+bean.getTotalPrice()+"'");
			sb.append(",'"+bean.getTbPrice()+"'");
			sb.append(",'"+bean.getLatnId()+"'");
			sb.append(",'"+bean.getFlag()+"'");
			sb.append(")");
			_log.debug("insertTmallFluxLog  sql:"+sb.toString());
			sessionFactory.getCurrentSession().createSQLQuery(sb.toString()).executeUpdate();
//			sessionFactory.getCurrentSession().saveOrUpdate(bean);
		} catch (Exception e) {
			e.printStackTrace();
			_log.info("异常= {}",e.getMessage());
		}
	}
	
	@Transactional(value = "transactionManager")
	public int getTmallFlux(String tbOrderNo){
    	 StringBuilder sb = new StringBuilder();
    	 sb.append("select count(1) from t_mall_flux_log a where a.tbOrderNo="+tbOrderNo);
    	 Query query = sessionFactory.getCurrentSession().createSQLQuery(sb.toString());
    	 BigDecimal  a=(BigDecimal)query.list().get(0);
		 return a.intValue();
	}

	@Transactional(value = "transactionManager")
	public void updateTmallFluxLog(TmallFluxLog tmallFluxLog) {
		StringBuilder sb = new StringBuilder();
		sb.append("update t_mall_flux_log set flag="+tmallFluxLog.getFlag());
		if(tmallFluxLog.getSalesIndentId()!=null){
			sb.append(",SalesIndentId='"+tmallFluxLog.getSalesIndentId()+"'");
		}
		if(tmallFluxLog.getCustIndentNbr()!=null){
			sb.append(",CustIndentNbr='"+tmallFluxLog.getCustIndentNbr()+"'");
		}
		sb.append(" where tbOrderNo='"+tmallFluxLog.getTbOrderNo()+"'");
		_log.debug("updateTmallFluxLog  sql:"+sb.toString());
		sessionFactory.getCurrentSession().createSQLQuery(sb.toString()).executeUpdate();
	}
	
	
	@Transactional(value = "transactionManager")
	public Integer getQH(String area_name){
    	 StringBuilder sb = new StringBuilder();
    	 sb.append("select QH from area_stream_lte_t where area_name ='"+area_name+"'");
    	 Query query = sessionFactory.getCurrentSession().createSQLQuery(sb.toString());
		 return Integer.valueOf(query.list().get(0).toString());
	}
	
	@Transactional(value = "transactionManager")
	public String getAreaName(String area_name){
    	 StringBuilder sb = new StringBuilder();
    	 sb.append("select area_name from area_stream_lte_t where qh="+area_name);
    	 Query query = sessionFactory.getCurrentSession().createSQLQuery(sb.toString());
    	 if(query.list().size()==0){
    		 return null;
    	 }
		 return query.list().get(0).toString();
	}
	
}
